package uk.ac.lkl.lpp.xml;



import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import uk.ac.lkl.lpp.PedagogyPlan;


public abstract class ElementProcessor {
	/**
	 * type property
	 */
	public static final String P_TYPE = "type";
	/**
	 * name property
	 */
	public static final String P_NAME = "name";
	/**
	 * value property
	 */
	public static final String P_VALUE = "value";

    private String elementName;


    public ElementProcessor(String elementName) {
        this.elementName = elementName;
    }


    public String getElementName() {
        return elementName;
    }


    /**
     * Convert the in-memory representation to an XML representation.
     * 
     * @param plan
     *            the plan to use
     * @param document
     *            the document to use for creating elements
     * @param pedagogyPlanElement
     *            the parent element
     * 
     */
    public abstract void convertDataToElements(PedagogyPlan plan,
                                               Document document,
                                               Element pedagogyPlanElement);


    /**
     * Convert child elements of <code>parentElement</code> matching
     * <code>elementName</code>.
     * 
     * <p>
     * Question: throw ModelIntegrityException is model logic is broken - e.g.
     * two PedagogyModel nodes?
     * </p>
     * 
     * <p>
     * Answer: Yep. Makes sense. The validation of the XML is pretty poor at the
     * moment.
     * </p>
     * 
     * @param plan
     *            the plan to use
     * @param parentElement
     *            the parent element
     * 
     * @throws XMLException
     * 
     */
    public final void convertElementsToData(PedagogyPlan plan,
                                            Element parentElement)
            throws XMLException {
        // todo: add support for restricting the number of elements
        // that should be found.
        // e.g. only one of PedagogyModel in any given file?
        NodeList elementList = parentElement.getElementsByTagName(elementName);
        for (int i = 0; i < elementList.getLength(); i++) {
            Element childElement = (Element) elementList.item(i);
            convertElementToData(plan, childElement);
        }
    }


    public abstract void convertElementToData(PedagogyPlan plan, Element element)
            throws XMLException;

}
